package siyuan.run.nacos.security.oauth2.mysql.config;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.bouncycastle.cert.ocsp.Req;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.MediaType;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer;
import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;

import java.util.HashMap;

/**
 * @program: sy
 * @description: 配置资源服务器
 * @author: SY
 * @create: 2020-12-21 21:08
 **/
@Configuration
@EnableResourceServer
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class RescourConfig extends ResourceServerConfigurerAdapter {

    @Autowired
    private AuthenticationSuccessHandler successHandler;
    @Autowired
    private AuthenticationFailureHandler failureHandler;

    @Override
    public void configure(HttpSecurity http) throws Exception {
        http.antMatcher("/nacos-oauth2-mysql/**")
                .formLogin()
                .usernameParameter("username")
                .passwordParameter("password")
                .loginPage("/user/login")
                .successHandler(successHandler)
                .failureHandler(failureHandler)
                .and()
                .authorizeRequests();

        // 资源服务器是默认保护所有的接口的，所以需要放行注册接口
        http.authorizeRequests().antMatchers("/user/register").permitAll();

        http.csrf()
                .disable()
                .httpBasic()
                .disable()
                .exceptionHandling()
                .authenticationEntryPoint((request,response,exception) -> {
                    response.setContentType(MediaType.APPLICATION_JSON_UTF8_VALUE);
                    response.getWriter()
                            .write(new ObjectMapper().writeValueAsString(
                                    new HashMap(){
                                        {
                                            put("status", 403);
                                            put("error", "没有权限");
                                        }
                                    }
                                )
                            );
                })
                .and()
                .authorizeRequests()
                .antMatchers("/noauth")
                .permitAll();

    }
}
